﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;

namespace DHelpers.ExtensionsHelper
{
    public static class ExtensionEnumHelper
    {
        public static string GetDescription(this Enum value)
        {
            var fieldInfo = value.GetType().GetField(value.ToString());
            var attribute = Attribute.GetCustomAttribute(fieldInfo, typeof(DescriptionAttribute)) as DescriptionAttribute;
            return attribute == null ? value.ToString() : attribute.Description;
        }

        public static IDictionary<T, string> GetEnumValuesAndDescription<T>()
        {
            var values = (Enum.GetValues(typeof (T))
                .Cast<T>()
                .Select(e =>
                    new
                    {
                        Key = e,
                        Description =
                            string.IsNullOrEmpty((e as Enum).GetDescription())
                                ? e.ToString()
                                : (e as Enum).GetDescription()
                    }))
                .ToDictionary(t => t.Key, k => k.Description);
            return values;
        }
    }
}